/**
 * 
 */
package cn.edu.gxnu.dsa.list;

/**
 * @author Zhiyong
 *
 */
public class SqList implements IList {

	private Object[] listElement;
	private int curLen;

	/**
	 * 
	 */
	public SqList(int maxSize) {
		curLen = 0;
		listElement = new Object[maxSize];
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#clear()
	 */
	@Override
	public void clear() {
		curLen = 0;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#isEmpty()
	 */
	@Override
	public boolean isEmpty() {
		return (curLen == 0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#length()
	 */
	@Override
	public int length() {
		return curLen;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#get(int)
	 */
	@Override
	public Object get(int index) throws Exception {
		if ((index < 0) || (index > curLen - 1)) {
			throw new Exception("The No." + index + " element does not exist! current length is:"+curLen);
		} else {
			return listElement[index];
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#insert(int, java.lang.Object)
	 */
	@Override
	public void insert(int index, Object object) throws Exception {
		if (curLen == listElement.length) {
			throw new Exception("The sequence list is full!");
		} else if (index < 0 || index > curLen) {
			throw new Exception("The insert position is illegal!");
		} else {
			for (int i = curLen; i > index; i--) {
				listElement[i] = listElement[i - 1];
			}
			listElement[index] = object;
			curLen++;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#remove(int)
	 */
	@Override
	public void remove(int index) throws Exception {
		if (index < 0 || index > curLen - 1) {
			throw new Exception("The remove position is illegal!");
		} else {
			for (int i = index; i < curLen; i++) {
				listElement[i] = listElement[i + 1];
			}
			curLen--;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#indexOf(java.lang.Object)
	 */
	@Override
	public int indexOf(Object object) {
		int i = 0;
		while (i < curLen && !listElement[i].equals(object)) {
			i++;
		}

		if (i < curLen) {
			return i;
		} else {
			return -1;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.gxnu.dsa.list.IList#display()
	 */
	@Override
	public void display() {
		System.out.println("The sequence list's details are below:");
		for (int i = 0; i < curLen; i++) {
			System.out.print(listElement[i] + " ");
		}
		System.out.print('\n');
	}

	public Object[] getListElement() {
		return listElement;
	}

	public void setListElement(Object[] listElement) {
		this.listElement = listElement;
	}	

}
